package main

import (
	"fmt"
	"go-study/algorithm/standard"
)

// 如何实现反向 DNS 查找缓存

func main() {
	ipAddress := []string{"10.57.11.127", "121.57.61.129", "66.125.100.103"}
	urls := []string{"www.samsung.com", "www.samsung.net", "www.baidu.com"}
	dnsCache := NewDNSCache()
	for i, v := range ipAddress {
		dnsCache.insert(v, urls[i])
	}
	ip := ipAddress[1]
	result := dnsCache.searchDNSCache(ip)
	fmt.Println(result)
}

var charCount = 11

type DNSCache struct {
	root *standard.TrieNode
}

func (p *DNSCache) getIndexFromRune(char rune) int {
	if char == '.' {
		return 10
	} else {
		return int(char) - '0'
	}
}

func (p *DNSCache) getRuneFromIndex(i int) rune {
	if i == 10 {
		return '.'
	} else {
		return rune('0' + i)
	}
}

func (p *DNSCache) insert(ip, url string) {
	current := p.root
	for _, v := range []rune(ip) {
		index := p.getIndexFromRune(v)
		if current.Child[index] == nil {
			current.Child[index] = standard.NewTrieNode(charCount)
		}
		current = current.Child[index]
	}
	current.IsLeaf = true
	current.Url = url
}

func (p *DNSCache) searchDNSCache(ip string) string {
	current := p.root
	for _, v := range []rune(ip) {
		index := p.getIndexFromRune(v)
		if current.Child[index] == nil {
			return ""
		}
		current = current.Child[index]
	}
	if current != nil && current.IsLeaf {
		return current.Url
	}

	return ""
}

func NewDNSCache() *DNSCache {
	return &DNSCache{root: standard.NewTrieNode(charCount)}
}
